//
//  SecondShoppingCartVC.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/4/29.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "SecondShoppingCartVC.h"

#import "ShoppongCartModel.h"
#import "ShoppingCartCell.h"

#import "CartGoodsModel.h"

#import "ConfirmOrderViewController.h"

@interface SecondShoppingCartVC ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property (nonatomic,strong) UILabel *totalCountLB;//商品总数量

@property (nonatomic,strong) UIButton *managerGoodsBtn;//管理

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIView *bottomView;//底部商品总价view

@property (nonatomic,strong) UIButton *allSelectBtn;//全选btn

@property (nonatomic,strong) UILabel *totalLB;

@property (nonatomic,strong) UILabel *totalPriceLB;//总价lb

@property (nonatomic,strong) UIButton *payBtn;//结算按钮

@property (nonatomic,strong) UIButton *deleteBtn;//删除按钮

@property (nonatomic,assign) BOOL isAllSelect;//是否全部选中

@property (nonatomic,strong) NSMutableArray *dataSourceArr;//数据源数组

@property (nonatomic,strong) NSMutableArray *selectGoodsArr;//选中商品数组

@property (nonatomic,assign) BOOL deleteStatus;//删除状态  默认为NO

@end

@implementation SecondShoppingCartVC


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([UserInfomationManager shareManager].loginStatus == YES) {
        [self getData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topTitle = @"购物车";
    self.view.backgroundColor = MainBackColor;
    self.topNavView.backgroundColor = MainBackColor;
    
    self.dataSourceArr = [NSMutableArray array];
    self.selectGoodsArr = [NSMutableArray array];
    self.isAllSelect = NO;
    self.deleteStatus = NO;
    
    [self initUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshSource:) name:@"refreshShoppingCartNoti" object:nil];
}
-(void)refreshSource:(NSNotification *)noti{
    [self getData];
}

#pragma mark - data
-(void)getData{
    self.dataSourceArr = [NSMutableArray array];
    self.selectGoodsArr = [NSMutableArray array];
    self.isAllSelect = NO;
    self.deleteStatus = NO;
    
    [NetWorkingCart getCartListWithSuccessBlock:^(id  _Nonnull responseObj) {
        [self.tableView.mj_header endRefreshing];
        
        NSDictionary *data = responseObj[@"data"];
        NSArray *carts = data[@"carts"];
        for (NSDictionary *dic in carts) {
            ShoppongCartModel *model = [ShoppongCartModel paraWithDict:dic];
            [self.dataSourceArr addObject:model];
        }
        [self.tableView reloadData];
        
        NSInteger totalCount = [data[@"cartSum"] integerValue];
        self.totalCountLB.text = [NSString stringWithFormat:@"共%ld件宝贝",(long)totalCount];
        [self updateBottomInfo];
        
        [self setDeleteStatusClick];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
    });
}

#pragma mark - UI
-(void)initUI{
    [self.view addSubview:self.totalCountLB];
    [self.view addSubview:self.managerGoodsBtn];
    [self.view addSubview:self.tableView];
    
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.allSelectBtn];
    [self.bottomView addSubview:self.totalLB];
    [self.bottomView addSubview:self.totalPriceLB];
    [self.bottomView addSubview:self.payBtn];
    [self.bottomView addSubview:self.deleteBtn];
}
#pragma mark - lazy
- (UILabel *)totalCountLB{
    if (!_totalCountLB) {
        _totalCountLB = [[UILabel alloc] initWithFrame:CGRectMake(15, kHeight_NavBar+15, 200, 20)];
        _totalCountLB.textAlignment = NSTextAlignmentLeft;
        _totalCountLB.font = FontSet(12);
        _totalCountLB.text = @"共0件宝贝";
    }
    return _totalCountLB;
}
- (UIButton *)managerGoodsBtn{
    if (!_managerGoodsBtn) {
        _managerGoodsBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _managerGoodsBtn.frame = CGRectMake(ScreenWidth-50, self.totalCountLB.top-5, 40, 30);
        [_managerGoodsBtn setTitle:@"管理" forState:normal];
        [_managerGoodsBtn setTitleColor:MainPureColor(85) forState:normal];
        [_managerGoodsBtn.titleLabel setFont:FontSet(13)];
        [_managerGoodsBtn addTarget:self action:@selector(managerGoodsClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _managerGoodsBtn;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.totalCountLB.bottom+5, ScreenWidth, ScreenHeight - self.totalCountLB.bottom - 5 - kSafe_Bottom - 50) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = MainBackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
    }
    return _tableView;
}
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight - kSafe_Bottom-50, ScreenWidth, 50+kSafe_Bottom)];
        _bottomView.backgroundColor = UIColor.whiteColor;
        
        UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(40, 15, 40, 20)];
        lb.text = @"全选";
        lb.font = FontSet(14);
        lb.textColor = MainBlackTextColor;
        lb.textAlignment = NSTextAlignmentLeft;
        [_bottomView addSubview:lb];
        lb.userInteractionEnabled = YES;
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        tap.delegate = self;
        [lb addGestureRecognizer:tap];
        
        UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        lineV.backgroundColor = MainBackColor;
        [_bottomView addSubview:lineV];
    }
    return _bottomView;
}
- (UIButton *)allSelectBtn{
    if (!_allSelectBtn) {
        _allSelectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _allSelectBtn.frame = CGRectMake(15, 17, 16, 16);
        [_allSelectBtn setImage:LoadImage(@"购物车_未选中") forState:normal];
        [_allSelectBtn addTarget:self action:@selector(selectGoodClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _allSelectBtn;
}

- (UILabel *)totalLB{
    if (!_totalLB) {
        _totalLB = [[UILabel alloc] initWithFrame:CGRectMake(95, 15, 50, 20)];
        _totalLB.text = @"合计：";
        _totalLB.font = FontSet(14);
        _totalLB.textColor = MainBlackTextColor;
        _totalLB.textAlignment = NSTextAlignmentLeft;
    }
    return _totalLB;
}
- (UILabel *)totalPriceLB{
    if (!_totalPriceLB) {
        _totalPriceLB = [[UILabel alloc] initWithFrame:CGRectMake(self.totalLB.right + 5, 16, ScreenWidth - 140 - 100, 18)];
        _totalPriceLB.text = @"0.00";
        _totalPriceLB.font = FontSet(17);
        _totalPriceLB.textColor = MainBlackTextColor;
        _totalPriceLB.textAlignment = NSTextAlignmentLeft;
    }
    return _totalPriceLB;
}

- (UIButton *)payBtn{
    if (!_payBtn) {
        _payBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _payBtn.frame = CGRectMake(ScreenWidth - 95, 7, 80, 36);
        _payBtn.clipsToBounds = YES;
        _payBtn.layer.cornerRadius = 18;
        _payBtn.backgroundColor = MainThemeColor;
        [_payBtn.titleLabel setFont:FontSet(14)];
        [_payBtn setTitleColor:UIColor.whiteColor forState:normal];
        [_payBtn setTitle:@"结算(0)" forState:normal];
        [_payBtn addTarget:self action:@selector(payClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _payBtn;
}
- (UIButton *)deleteBtn{
    if (!_deleteBtn) {
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteBtn.frame = CGRectMake(ScreenWidth - 95, 7, 80, 36);
        _deleteBtn.clipsToBounds = YES;
        _deleteBtn.layer.cornerRadius = 18;
        _deleteBtn.backgroundColor = RGB(238, 10, 36);
        [_deleteBtn.titleLabel setFont:FontSet(14)];
        [_deleteBtn setTitleColor:UIColor.whiteColor forState:normal];
        [_deleteBtn setTitle:@"删除" forState:normal];
        _deleteBtn.hidden = YES;
        [_deleteBtn addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}


#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShoppongCartModel *model = self.dataSourceArr[indexPath.row];
    return model.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShoppingCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShoppingCartCell"];
    if (!cell) {
        cell = [[ShoppingCartCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ShoppingCartCell"];
    }
    cell.model = self.dataSourceArr[indexPath.row];
    [cell setUpdateShopStatusBlock:^(ShoppongCartModel * _Nonnull shopM) {
        [self updateCartStatus:shopM];
    }];
    return cell;
}

#pragma mark - SEL

-(void)tapClick:(UIGestureRecognizer *)ges{
    [self selectGoodClick];
}

//全选按钮
-(void)selectGoodClick{
    self.isAllSelect = !self.isAllSelect;
    self.selectGoodsArr = [NSMutableArray array];
    [self setGoodsSelect];
}
//全选/全不选
-(void)setGoodsSelect{
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i<self.dataSourceArr.count; i++) {
            ShoppongCartModel *model = self.dataSourceArr[i];
            NSMutableArray *muProdArr = [NSMutableArray array];
            for (int p = 0; p<model.products.count; p++) {
                CartGoodsModel *cartM = model.products[p];
                cartM.isSelect = self.isAllSelect;
                [muProdArr addObject:cartM];
                if (self.isAllSelect == YES) {
                    [self.selectGoodsArr addObject:cartM];
                }
            }
            model.products = (NSArray *)muProdArr;
            [self.dataSourceArr replaceObjectAtIndex:i withObject:model];
        }
        [self.tableView reloadData];
        [self updateBottomInfo];
    });
}

//管理购物车
-(void)managerGoodsClick{
    self.deleteStatus = !self.deleteStatus;
    [self setDeleteStatusClick];
}
//设置编辑状态下的UI
-(void)setDeleteStatusClick{
    [self.managerGoodsBtn setTitle:self.deleteStatus == YES ? @"完成":@"管理" forState:normal];
    self.deleteBtn.hidden = !self.deleteStatus;
    self.payBtn.hidden = self.deleteStatus;
}

//更新购物车状态
-(void)updateCartStatus:(ShoppongCartModel *)shopM{
    for (int i = 0; i<self.dataSourceArr.count; i++) {
        ShoppongCartModel *model = self.dataSourceArr[i];
        if ([model.company isEqualToString:shopM.company]) {
            [self.dataSourceArr replaceObjectAtIndex:i withObject:model];
        }
    }
//    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
    [self.tableView reloadData];
    
    self.selectGoodsArr = [NSMutableArray array];
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i<self.dataSourceArr.count; i++) {
            ShoppongCartModel *model = self.dataSourceArr[i];
            for (int p = 0; p<model.products.count; p++) {
                CartGoodsModel *cartM = model.products[p];
                if (cartM.isSelect == YES) {
                    [self.selectGoodsArr addObject:cartM];
                }
            }
        }
        [self updateBottomInfo];
    });
}
//更新底部信息
-(void)updateBottomInfo{
        
    dispatch_async(dispatch_get_main_queue(), ^{
        NSInteger count = 0;
        for (int i = 0; i<self.dataSourceArr.count; i++) {
            ShoppongCartModel *model = self.dataSourceArr[i];
            for (int p = 0; p<model.products.count; p++) {
                count = count+1;
            }
        }
        if (self.selectGoodsArr.count == count) {
            self.isAllSelect = YES;
        }else{
            self.isAllSelect = NO;
        }
        
        [self.allSelectBtn setImage:self.isAllSelect == YES?LoadImage(@"购物车_选中"):LoadImage(@"购物车_未选中") forState:normal];
        if (self.selectGoodsArr.count <= 0) {
            [self.allSelectBtn setImage:LoadImage(@"购物车_未选中") forState:normal];
        }
        
        NSInteger goodsCount = 0;
        float price = 0;
        NSInteger tbPrice = 0;
        for (CartGoodsModel *model in self.selectGoodsArr) {
            goodsCount = goodsCount + model.number;
            price = price + model.price*model.number;
            tbPrice = tbPrice + model.tbprice*model.number;
        }
        self.totalPriceLB.text = [Configuration getTotalPriceWithPrice:price withTbPrice:tbPrice];
        [self.payBtn setTitle:[NSString stringWithFormat:@"结算(%ld)",(long)goodsCount] forState:normal];
    });
}

//去结算
-(void)payClick{
    if (self.selectGoodsArr.count <= 0) {
        [[XNProgressHUD shared] showWithTitle:@"您还未选择商品！"];
        return;
    }
    
    NSMutableArray *skuIds = [NSMutableArray array];
    for (CartGoodsModel *model in self.selectGoodsArr) {
        [skuIds addObject:[NSString stringWithFormat:@"%ld",model.skuId]];
    }
    
    ConfirmOrderViewController *vc = [[ConfirmOrderViewController alloc] init];
    vc.module = @"cart";
    vc.skuIds = skuIds;
    [self.navigationController pushViewController:vc animated:YES];
}
//删除
-(void)deleteClick{
    if (self.selectGoodsArr.count <= 0) {
        [[XNProgressHUD shared] showWithTitle:@"还未选中商品"];
        return;
    }
    NSMutableArray *arr = [NSMutableArray array];
    for (CartGoodsModel *cartM in self.selectGoodsArr) {
        [arr addObject:[NSString stringWithFormat:@"%ld",cartM.ID]];
    }
    [NetWorkingCart deleteCartListWithIds:arr withSuccessBlock:^(id  _Nonnull responseObj) {
        [[XNProgressHUD shared] showWithTitle:@"删除成功"];
        [self getData];
    }];
}



@end





